//
//  MPEditUserInfoTableViewController.m
//  SearchPeople
//
//  Created by YoloMao on 16/5/12.
//
//

#import "MPEditUserInfoTableViewController.h"
#import "MPEditViewController.h"
#import "MPImport.h"
#import "MPUser.h"
#import "UIImageView+WebCache.h"

@interface MPEditUserInfoTableViewController ()
<
UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
MPEditViewControllerDelegate
>

@property (weak, nonatomic) IBOutlet UIImageView *headIconImageView;
@property (weak, nonatomic) IBOutlet UILabel *ocupptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *genderLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneNumLabel;
@property (weak, nonatomic) IBOutlet UILabel *wechatLabel;
@property (weak, nonatomic) IBOutlet UILabel *qqNumLabel;
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;

@property (strong, nonatomic) NSString *user_id;

@property (strong, nonatomic) UIImagePickerController *imagePicker;

@property (strong, nonatomic) NSString *imageUrl;

@end

@implementation MPEditUserInfoTableViewController

#pragma mark - UIViewController Life Cycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:@"确定"
                                                            style:UIBarButtonItemStylePlain
                                                           target:self
                                                           action:@selector(confirmButtonClick)];
    self.navigationItem.rightBarButtonItem = item;
    [self getLocalUserData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Private method

- (void)getLocalUserData
{
    MPUser *user = [[[MPSettingsManager getInstance].userDefault objectForKey:@"user"]mutableCopy];
    self.user_id = [user valueForKey:@"user_id"];
    self.userNameLabel.text = [user valueForKey:@"user_name"];
    self.genderLabel.text = [user valueForKey:@"gender"];
    self.phoneNumLabel.text = [user valueForKey:@"mobile"];
    self.ocupptionLabel.text = [user valueForKey:@"ocuppytion"];
    self.qqNumLabel.text = [user valueForKey:@"qq"];
    self.wechatLabel.text = [user valueForKey:@"wechat"];
    self.imageUrl = [user valueForKey:@"headImage"];
    
    NSURL *url = [NSURL URLWithString:self.imageUrl];
    UIImage *image = [UIImage imageNamed:@"placeHolder"];
    [self.headIconImageView sd_setImageWithURL:url placeholderImage:image];
    self.headIconImageView.layer.masksToBounds = YES;
    self.headIconImageView.layer.cornerRadius = 35;
}

- (void)confirmButtonClick
{
    __weak typeof(self) weakSelf = self;
    [[MPDocumentHttpClient shareInstance] ModifyUserInfoWithUserID:self.user_id
                                                     WithHeadImage:self.imageUrl
                                                      WithBirthday:nil
                                                    WithOcuppytion:self.ocupptionLabel.text
                                                    WithBirthPlace:nil
                                                     WithLivePlace:nil
                                                            WithQQ:self.qqNumLabel.text
                                                        WithMobile:self.phoneNumLabel.text
                                                        WithWechat:self.wechatLabel.text
                                                        WithGender:self.genderLabel.text
                                                  WithSuccessBlock:^(MPRequest *request, MPResponse *response)
    {
        [SVProgressHUD showSuccessWithStatus:@"更新个人资料成功"];
        [weakSelf saveUserInfoAndPopViewController];
    } WithFailedBlock:^(MPRequest *request, MPResponse *response)
     {
         [SVProgressHUD showErrorWithStatus:@"更新个人资料失败"];
    }];
}

- (void)saveUserInfoAndPopViewController
{
    NSMutableDictionary *user = [[[MPSettingsManager getInstance].userDefault objectForKey:@"user"] mutableCopy];
    [user setObject:self.user_id forKey:@"user_id"];
    [user setObject:self.imageUrl forKey:@"headImage"];
    [user setObject:self.ocupptionLabel.text ? self.ocupptionLabel.text : @"" forKey:@"ocuppytion"];
    [user setObject:self.qqNumLabel.text ? self.qqNumLabel.text : @"" forKey:@"qq"];
    [user setObject:self.phoneNumLabel.text ? self.phoneNumLabel.text : @"" forKey:@"mobile"];
    [user setObject:self.wechatLabel.text ? self.wechatLabel.text : @"" forKey:@"wechat"];
    [user setObject:self.genderLabel.text ? self.genderLabel.text : @"" forKey:@"gender"];
    [[MPSettingsManager getInstance].userDefault setObject:user forKey:@"user"];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)pushToEditViewControllerWithUserInfoType:(MPUserInfoType)type
{
    MPEditViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"MPEditViewController"];
    switch (type)
    {
        case MPUserInfoTypeOcupption:
            controller.title = @"职业";
            controller.text = self.ocupptionLabel.text;
            break;
        case MPUserInfoTypePhoneNum:
            controller.title = @"手机";
            controller.text = self.phoneNumLabel.text;
            break;
        case MPUserInfoTypeWeChat:
            controller.title = @"微信";
            controller.text = self.wechatLabel.text;
            break;
        case MPUserInfoTypeQQNum:
            controller.title = @"QQ";
            controller.text = self.qqNumLabel.text;
            break;
        case MPUserInfoTypeGender:
            controller.title = @"性别";
            controller.gender = self.genderLabel.text;
            break;
        default:
            break;
    }
    controller.delegate = self;
    controller.userInfoType = type;
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark - MPEditViewControllerDelegate

- (void)updateUserInfoWithString:(NSString *)string withType:(MPUserInfoType)type
{
    switch (type)
    {
        case MPUserInfoTypeOcupption:
            self.ocupptionLabel.text = string;
            break;
        case MPUserInfoTypePhoneNum:
            self.phoneNumLabel.text  = string;
            break;
        case MPUserInfoTypeWeChat:
            self.wechatLabel.text    = string;
            break;
        case MPUserInfoTypeQQNum:
            self.qqNumLabel.text     = string;
            break;
        case MPUserInfoTypeGender:
            self.genderLabel.text    = string;
            break;
        default:
            break;
    }
}

#pragma mark - TableView Delegate 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {//头像
        __weak typeof(self) weakSelf = self;
        [UIActionSheet showInView:self.view withTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"拍照", @"从相册中选取"] tapBlock:^(UIActionSheet * _Nonnull actionSheet, NSInteger buttonIndex)
         {
             if (buttonIndex == 1)
             {
                 [weakSelf.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
                 [weakSelf presentViewController:self.imagePicker animated:YES completion:nil];
             }else if (buttonIndex == 0)
             {
                 if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
                 {
                     [weakSelf.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
                     [weakSelf presentViewController:self.imagePicker animated:YES completion:nil];
                 }else
                 {
                     [weakSelf.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
                     [weakSelf presentViewController:self.imagePicker animated:YES completion:nil];
                 }
             }
         }];
    }
    else if (indexPath.row == 1)
    {//职业
        [self pushToEditViewControllerWithUserInfoType:MPUserInfoTypeOcupption];
    }
    else if (indexPath.row == 2)
    {//性别
        [self pushToEditViewControllerWithUserInfoType:MPUserInfoTypeGender];
    }
    else if (indexPath.row == 3)
    {//手机
        [self pushToEditViewControllerWithUserInfoType:MPUserInfoTypePhoneNum];
    }
    else if (indexPath.row == 4)
    {//微信
        [self pushToEditViewControllerWithUserInfoType:MPUserInfoTypeWeChat];
    }
    else if (indexPath.row == 5)
    {// QQ
        [self pushToEditViewControllerWithUserInfoType:MPUserInfoTypeQQNum];
    }
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [SVProgressHUD show];
    UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];
    
    NSData *imgData= UIImageJPEGRepresentation(image,0.1);
    
    UIImage *headIconImage = [UIImage imageWithData:imgData];
    
    __weak typeof(self) weakSelf = self;
    [picker dismissViewControllerAnimated:YES completion:^{
        if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
        {
            UIImageWriteToSavedPhotosAlbum(image, weakSelf, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
        }
        weakSelf.headIconImageView.image = headIconImage;
        weakSelf.headIconImageView.layer.masksToBounds = YES;
        weakSelf.headIconImageView.layer.cornerRadius = 35;
        
        [[MPDocumentHttpClient shareInstance]uploadImage:headIconImage
                                        WithSuccessBlock:^(MPRequest *request, MPResponse *response)
        {
            weakSelf.imageUrl = response.errorMsg;
            [SVProgressHUD dismiss];
        } WithFailedBlock:^(MPRequest *request, MPResponse *response)
        {
            [SVProgressHUD dismiss];
        }];
    }];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo
{
    NSLog(@"保存图片%@",error != NULL ? @"失败" : @"成功");
}

#pragma mark - Getter && Setter

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker)
    {
        _imagePicker = [[UIImagePickerController alloc] init];
        
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

@end